<?php

namespace app\logic\single\group;

use app\api\controller\group\GroupGoods;
use app\api\model\group\GroupGoodsApiModel;
use app\api\model\group\GroupOrderApiModel;
use app\api\model\order\OrderEntityApiModel;
use app\api\model\order\OrderEntityDetailApiModel;
use app\api\model\user\UserWriterWaterApiModel;
use app\logic\model\user\UserLogicModel;
use app\logic\single\GoodsSingle;
use app\logic\single\pay\WxPaySingle;
use app\logic\single\UserGoodsSingle;
use app\logic\single\UserMusicSingle;
use Snow\Snow;
use think\facade\Db;

class GroupOrderSingle
{
    private static $inc;
    /**
     * @var GroupOrderApiModel
     */
    private $orderModel;
    /**
     * @var GroupGoodsApiModel
     */
    private $goodsModel;
    /**
     * @var UserWriterWaterApiModel
     */
    private $userWriterWaterModel;



    private function __clone(){

    }
    // 禁止被实例化
    private function __construct()
    {
        $this->orderModel = new GroupOrderApiModel();
        $this->goodsModel = new GroupGoodsApiModel();
        $this->userWriterWaterModel = new UserWriterWaterApiModel();
    }
    public static function getInstance(){
        if(is_null(self::$inc)){
            self::$inc = new self();
        }
        return self::$inc;
    }

    /**
     * 订单完成
     * @param string $order_id
     * @param int $pay_type
     * @return array
     */
    public function complete(string $order_id='', int $pay_type = 10, array $other = []): array
    {
        $order = $this->orderModel->where('id',$order_id)->find();
        if(empty($order)){
            $order = $this->orderModel->where('order_no',$order_id)->find();
        }
        if(empty($order)){
            return [-1,'订单不存在'];
        }
        if($order['status'] != 10){//如果已完成，则不能支付
            return [-1,'订单不能完成'];
        }
        $goods = $this->goodsModel->getFindById($order['goods_id']);
        Db::startTrans();
        try{
            //修改订单状态
            $order->pay_type = $pay_type;
            $order->status = 20;
            $order->pay_time = date('Y-m-d H:i:s');
            if(isset($other['trade_no'])){
                $order->trade_no = $other['trade_no'];
            }
            $order->save();
            //查询拼团是否完成
            $num = $this->orderModel->getApiBuyNum($goods,$goods['id']);
            if($num >= $goods['complete_num']){
                //完成
                $this->goodsComplete($goods);
            }
            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            return [-1,$exception->getMessage()];
        }
        return [1,'成功'];
    }

    private function goodsComplete($goods)
    {
        //先修改商品信息
        $goods->is_complete = 20 ;
        $goods->complete_time = date('Y-m-d H:i:s');
        $goods->save();

        //获取音乐商品信息
        $goods_id_arr[]=
            [
                'goods_id'=>$goods['goods_id'],
                'type'=>$goods['type'],
            ];
        $goods_list = GoodsSingle::getInstance()->getGoodsList($goods_id_arr);
        $music_arr = GoodsSingle::getInstance()->getMusicByGoodsList($goods_list);
        //完成每个订单信信息
        $orders = $this->orderModel
            ->where('goods_id',$goods['id'])
            ->where('status',20)
            ->column('*');
        $orders_id_arr = array_column($orders,'id');
        $this->orderModel
            ->whereIn('id',$orders_id_arr)
            ->save(['status'=>30,]);
        //组装各种信息
        $writer = UserLogicModel::getInfoById($orders[0]['sell_id']);
        $user_goods_arr =[];
        $user_music_arr =[];
        foreach ($orders as $val){
            $can_see = 1;
            if(!empty($val['sell_id'])){
                if(!empty($writer)){
                    if($val['writer_price'] > $writer['order_audit_price']){
                        //如果需要审核金额比订单金额大，则需要审核 比如 订单金额：100 审核：50
                        $can_see = -1;
                    }
                }
            }
            if($can_see == 1){
                $inc_goods_sale[]=[
                    'goods_id'=>$goods['goods_id'],
                    'type'=>$goods['type'],
                ];
                if(!empty($val['sell_id'])){
                    $writer_water_insert[]=[
                        'user_id'=>$val['sell_id'],
                        'type' => 2,
                        'price'=>$val['writer_price'],
                        'source'=>30,
                        'order_id'=>$val['id'],
                        'order_detail_id'=>$val['id'],
                        'remark'=>'出售拼团商品获得佣金'.$val['writer_price'] . '元',
                        'music_type'=>$goods['type'],
                    ];
                    $this->orderModel->where('id',$val['id'])->update(['writer_can_see'=>1]);
                }
            }

            if(!empty($inc_goods_sale)){
                GoodsSingle::getInstance()->IncSales($inc_goods_sale);
            }
            //给予用户音乐
            if(!empty($music_arr)){
                foreach ($music_arr as $music_val){
                    if(!UserMusicSingle::getInstance()->isHave($val['id'],$val['buyer_id'])){
                        $user_music_arr[]=[
                            'user_id'=>$val['buyer_id'],
                            'music_id'=>$music_val['id'],
                            'source'=>'订单',
                            'create_time'=>date('Y-m-d H:i:s'),
                        ];
                    }
                }

            }
            if(!empty($goods_id_arr)){
                //给予用户商品
                foreach ($goods_id_arr as $goods_val){
                    if(!UserGoodsSingle::getInstance()->isHave($goods_val['goods_id'],$goods_val['type'],$val['buyer_id'])){
                        $user_goods_arr[]=[
                            'user_id'=>$val['buyer_id'],
                            'goods_id'=>$goods_val['goods_id'],
                            'type'=>$goods_val['type'],
                            'source'=>'订单',
                            'create_time'=>date('Y-m-d H:i:s'),
                        ];
                    }

                }

            }
        }
        //给予作家佣金
        if(!empty($writer_water_insert)){
            $this->userWriterWaterModel->saveAll($writer_water_insert);
        }
        if(!empty($user_music_arr)){
            UserMusicSingle::getInstance()->saves($user_music_arr);
        }
        if(!empty($user_goods_arr)){
            UserGoodsSingle::getInstance()->saves($user_goods_arr);
        }
    }


    public function cancle($order_id)
    {
        $order = $this->orderModel->getFindById($order_id);
        if(empty($order)){
            return '订单不存在';
        }
        if($order['status'] != 10){
            return '该订单不能取消';
        }
        Db::startTrans();
        try{
            //修改运单状态
            $order->save(['status'=>-10,'cancel_time'=>date('Y-m-d H:i:s')]);
            //如果有优惠券，返还优惠券
            Db::commit();
            return true;
        }catch (\Exception $exception){
            Db::rollback();
            return $exception->getMessage();
        }
    }

    public function apply_refund($order_id)
    {
        $order = $this->orderModel->getFindById($order_id);
        if(empty($order)){
            return '订单不存在';
        }
        if(!$order['status'] != 20){
            return '该订单不能退款';
        }
        if(empty($order['refund_order_no'])){
            $order->refund_order_no = Snow::createOnlyId();
            $order->save();
        }
        //判断支付信息
        switch ($order_id['pay_type']){
            case '10':
                //todo 支付宝退款

                break;
            case 20:
                //todo 微信退款
                $res = WxPaySingle::getInstance()->refund($order,'group');
                break;
        }
        return $res;
    }

    function refund($order_no=''){
        $order = $this->orderModel->where('order_no',$order_no);
        if(empty($order)){
            return '订单不存在';
        }
        if(!$order['status'] != 20){
            return '该订单不能退款';
        }
        $order->status =-20;
        $order->refund_time = date('Y-m-d H:i:s');
        $order->save();
    }
}